package com.gfxy.modules.items.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gfxy.modules.common.entity.MemberList;
import com.gfxy.modules.common.service.IMemberListService;
import com.gfxy.modules.common.service.ScoreUpdate;
import com.gfxy.modules.common.service.impl.CurrentDateService;
import com.gfxy.modules.items.entity.Kygl;
import com.gfxy.modules.items.mapper.KyglMapper;
import com.gfxy.modules.items.service.IKyglService;
import com.gfxy.modules.excel.ExcelUtil;
import com.gfxy.modules.items.vo.KyglVo;
import com.gfxy.modules.items.vo.ZyyxsztsjhMemberPage;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.checkerframework.checker.units.qual.A;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.ImportExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class KyglServiceImpl extends AbstractProjectServiceImpl<KyglMapper, Kygl> implements IKyglService {

    @Autowired
    private ScoreUpdate scoreUpdate;
    @Autowired
    private CurrentDateService currentDateService;

    @Autowired
    private IMemberListService memberListService;

    @Override
    public Double getTotalScore(Kygl kygl) {
        return 0.0;
    }

    @Override
    protected Kygl getOneProject(Row row) {
        return null;
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public Result<?> importExcel(MultipartFile file) throws IOException {

        int SHEET_NUM = 0;
        int errorLines = 0;
        int successLines = 0;
        List<String> errorMessage = new ArrayList<>();

        InputStream inputStream = file.getInputStream();
        if (!(inputStream).markSupported()) {
            inputStream = new PushbackInputStream(inputStream, 8);
        }
        Workbook book = WorkbookFactory.create(inputStream);
        Sheet sheet = book.getSheetAt(0);



        String date = this.currentDateService.getCurrentDate().getCurrentDate();
        this.delete(date);

        String work_no = "";
        String depId = "";
        String totalScore ="";

        List<Kygl> kygls = new ArrayList<>(sheet.getLastRowNum());
        List<MemberList> memberLists = new ArrayList<>(sheet.getLastRowNum());
        for (int i = 3; i <= sheet.getLastRowNum(); i++) {

            try {
                Row row = sheet.getRow(i);
                String work_no_temp = ExcelUtil.formatCell(row.getCell(1));

                String totalScoreTemp = ExcelUtil.formatCell(row.getCell(13)).trim();

                if(!totalScoreTemp.trim().isEmpty()){
                    totalScore = totalScoreTemp;
                }


                if (!work_no_temp.isEmpty()) {
                    work_no = work_no_temp;
                    depId = this.baseMapper.queryTeachingDepId(work_no);
                }

                if(!totalScore.equals("0")){
                    String projectName = ExcelUtil.formatCell(row.getCell(11));
                    String scoreStr = ExcelUtil.formatCell(row.getCell(15));
                    Double score = scoreStr.isEmpty() ? 0.0 : Double.parseDouble(scoreStr);
                    String rollK = ExcelUtil.formatCell(row.getCell(12));
                    if (!projectName.isEmpty()) {

                        String id = IdWorker.getIdStr();
                        Kygl research_temp = new Kygl();
                        research_temp = new Kygl();
                        research_temp.setId(id);
                        research_temp.setDate(date);
                        research_temp.setProjectName(projectName);
                        research_temp.setTotalScore(score);
                        research_temp.setRoleK(rollK);



                        MemberList memberList = new MemberList();
                        memberList.setItemValue(research_temp.itemValue);
                        memberList.setDate(date);
                        memberList.setItemId(id);
                        memberList.setRanked(1);
                        memberList.setTeacherId(work_no);
                        memberList.setOrgId(depId);
                        memberList.setScore(score);


                        kygls.add(research_temp);
                        memberLists.add(memberList);
//                        this.saveMain(research_temp, memberListList);
                    }
                }
                successLines++;
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                errorMessage.add("excel 第 " + i + "行数据解析出现位置异常; ");
            }
        }

        this.saveBatch(kygls);
        this.memberListService.saveBatch(memberLists);
        memberLists.forEach(result->{
            scoreUpdate.updataNewScore(result);
        });

        return ImportExcelUtil.imporReturnRes(errorLines, successLines, errorMessage);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public void delete(String date) {
        this.baseMapper.deleteMemberList(date);
        this.baseMapper.deleteItems(date);
    }


    @Override
    public List<KyglVo> selectListPage(String date, String teacherId) {
        List<KyglVo> page1 = baseMapper.selectMemberPageListByYear(date,teacherId);
        return page1;
    }
}
